package com.zizo.autohome.carinfo.address;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.zizo.util.ConnectionPool;

public class AddressDao {
	private Connection conn = ConnectionPool.getConnection();

	public String getContent(String flag) throws IOException {
		InputStream is = this.getClass().getResourceAsStream("" + flag + ".txt");
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		String temp = "";
		StringBuffer sb = new StringBuffer();
		while ((temp = br.readLine()) != null) {
			sb.append(temp);
		}
		return sb.toString();
	}

	public void parse(String s) throws JSONException {
		JSONArray json = new JSONArray(s);
		for (int i = 0; i < json.length(); i++) {
			JSONObject jobj = json.getJSONObject(i);
			int ProvinceId = jobj.getInt("ProvinceId");
			String FirstCharacter = jobj.getString("FirstCharacter");
			String Pinyin = jobj.getString("Pinyin");
			int Id = jobj.getInt("Id");
			String Name = jobj.getString("Name");
			insert(ProvinceId, FirstCharacter, Pinyin, Id, Name);
		}
	}

	public void insert(int pid, String l, String p, int id, String name) {
		PreparedStatement ps = null;
		String sql = "INSERT INTO autohome_syn.other_address(provinceId,firstCharacter,pinyin,addId,name) values(?,?,?,?,?)";
		try {
			ps = conn.prepareStatement(sql);
			ps.setInt(1, pid);
			ps.setString(2, l);
			ps.setString(3, p);
			ps.setInt(4, id);
			ps.setString(5, name);
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws IOException, JSONException {
		AddressDao dao = new AddressDao();
		String s = dao.getContent("pro");
		dao.parse(s);
		String ss = dao.getContent("city");
		dao.parse(ss);
	}
}
